// 文章管理

package info

import (
	"api/common"
	"api/common/logger"
	"api/common/web"
	"api/models"
	"encoding/base64"
	"io"
	"net/http"
	"os"
)

// @TagName 文章管理
// @Controller ContentController
type ContentController struct{}

// @Title 文章列表数据
// @Route /content/list --> List
// @Method post
func (this *ContentController) List(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.TokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	model := &models.Content{}
	fields := "id,navi_id,user_id,title,abstract,mark_img,recommend," +
		"browse_num,like_num,share_num,share_url,sequ,add_time"
	web.JsonCallBakFilter(w, inputJson, model, fields, "", "")
}

// @Title 新增文章信息
// @Route /content/create --> Create
// @Method post
func (this *ContentController) Create(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.CreateRecord(w, r, &models.Content{})
}

// @Title 编辑文章信息
// @Route /content/edit --> Edit
// @Method post
func (this *ContentController) Edit(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.EditRecord(w, r, &models.Content{})
}

// @Title 删除文章信息
// @Route /content/delete --> Delete
// @Method post
func (this *ContentController) Delete(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.DeleteCallBak(w, r, &models.Content{})
}

// @Title 文章信息回显
// @Route /content/echo --> Echo
// @Method post
func (this *ContentController) Echo(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.EchoCallBak(w, r, &models.Content{})
}

// @Title 上传封面图片或文章内容图片
// @Route /content/upload --> Upload
// @Param {"userId":1,"token":"a","b64":"base64Code","b64sm":"base64Code","imgType":"jpg","contentId":1}
// @Method post
func (this *ContentController) Upload(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.TokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	b64 := inputJson["b64"]
	b64sm := inputJson["b64sm"]
	imgType := inputJson["imgType"]
	contentId := inputJson["contentId"]

	if b64 == nil || b64 == "" {
		web.ServeJSON(w, web.JsonMsg{false, "图片数据不能为空", 1})
		return
	}
	if imgType == nil {
		web.ServeJSON(w, web.JsonMsg{false, "图片扩展名不能为空", 1})
		return
	}

	imgStr, err := base64.StdEncoding.DecodeString(b64.(string))
	if err != nil {
		logger.Error("源图格式不正确", err)
		web.ServeJSON(w, web.JsonMsg{false, "源图格式不正确" + err.Error(), 1})
		return
	}

	filePath := "info/" + common.GetNowWithFormat("200601") + "/"
	fileName := ""
	if contentId == nil {
		fileName = common.GetNowWithFormat("02030405")
	} else {
		fileName = common.ToStr(contentId)
	}
	fileUrl := filePath + fileName + "." + common.ToStr(imgType)

	// 绝对路径(防止"MkdirAll"将文件夹创建在"C:\Windows\System32")
	absPath := common.Config.UploadPath
	err = common.CreateChildDir(absPath + filePath)
	if err != nil {
		logger.Error("创建文件夹发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "创建文件夹发生错误" + err.Error(), 1})
		return
	}

	file, err := os.Create(absPath + fileUrl)
	if err != nil {
		logger.Error("创建图片文件发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "创建图片文件发生错误" + err.Error(), 1})
		return
	}
	_, err = io.WriteString(file, string(imgStr))
	_ = file.Close()
	if err != nil {
		logger.Error("保存图片文件发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "保存图片文件发生错误" + err.Error(), 1})
		return
	}

	// 缩略图的上传不是必须的，当源图尺寸小于400象素时，就没必要上传缩略图了
	if b64sm != nil && b64sm != "" {
		imgsmStr, err := base64.StdEncoding.DecodeString(b64sm.(string))
		if err != nil {
			logger.Error("缩略图格式不正确", err)
			web.ServeJSON(w, web.JsonMsg{false, "缩略图格式不正确" + err.Error(), 1})
			return
		}

		fileUrl = filePath + fileName + "_sm." + common.ToStr(imgType)

		file, err := os.Create(absPath + fileUrl)
		if err != nil {
			logger.Error("创建缩略图发生错误", err)
			web.ServeJSON(w, web.JsonMsg{false, "创建缩略图发生错误" + err.Error(), 1})
			return
		}
		_, err = io.WriteString(file, string(imgsmStr))
		_ = file.Close()
		if err != nil {
			logger.Error("保存缩略图发生错误", err)
			web.ServeJSON(w, web.JsonMsg{false, "保存缩略图发生错误" + err.Error(), 1})
			return
		}
	}

	result := map[string]interface{}{}
	result["status"] = 0
	result["success"] = true
	result["msg"] = "图片上传成功"
	result["imageUrl"] = fileUrl
	web.ServeJSON(w, result)
}
